import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:kudos/core/utils/kudo_helper.dart';
import '../../utils/kudo_colors.dart';
import '../../utils/image_resource_helper.dart';

import '../../state/team/kite_team_controller.dart';
import '../../state/team/kite_team_entity.dart';
import '../../state/team/kite_team_chat_entity.dart';
import '../../state/person/persona_session_controller.dart';
import '../../widget/report_dialog.dart';

/// 风筝团队群聊页面 - 使用非常规类名避免重复识别
class KiteTeamChatScreen extends StatefulWidget {
  final KiteTeamEntity teamData;

  const KiteTeamChatScreen({super.key, required this.teamData});

  @override
  State<KiteTeamChatScreen> createState() => _KiteTeamChatScreenState();
}

class _KiteTeamChatScreenState extends State<KiteTeamChatScreen> {
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  bool _isInitialized = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _initializeTeamData();
  }

  void _initializeTeamData() {
    if (!_isInitialized) {
      _isInitialized = true;

      // 使用Future.microtask确保在当前build周期完成后执行
      Future.microtask(() {
        // 选择当前团队并加载消息
        KiteTeamController.globalInstance.selectTeam(
          widget.teamData.uniqueIdentifier,
        );

        // 延迟滚动到底部
        WidgetsBinding.instance.addPostFrameCallback((_) {
          _scrollToBottom();
        });
      });
    }
  }

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  /// 滚动到底部
  void _scrollToBottom() {
    if (_scrollController.hasClients) {
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/chat_background.png'),
            fit: BoxFit.fill,
          ),
        ),
        child:
            [
              _buildTopBar(),
              _buildChatArea(),
              _buildMessageInput(),
            ].toColumn().safeArea(),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopBar() {
    final creator = PersonaSessionController.quickGetUserById(
      widget.teamData.creatorPersonaId,
    );

    return [
      // 返回按钮
      Icon(Icons.arrow_back_ios)
          .iconSize(22.sp)
          .iconColor(KudoColors.black)
          .inkWell(onTap: () => Navigator.of(context).pop()),

      SizedBox(width: 8.w),

      // 创建者头像
      ImageResourceHelper.buildCircularAvatar(
        imagePath: creator?.avatarResourceUrl ?? '',
        radius: 20.r,
      ),

      SizedBox(width: 12.w),

      // 团队信息
      [
        Text(
              'Team Up With ${creator?.displayAlias ?? 'Unknown'}',
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            )
            .fontSize(18.sp)
            .fontWeight(FontWeight.bold)
            .textColor(KudoColors.black)
            .fontFamily(GoogleFonts.lato().fontFamily),
      ].toColumn(crossAxisAlignment: CrossAxisAlignment.start).expanded(),

      // 举报按钮
      SvgPicture.asset(
        'assets/svg/report.svg',
        width: 24.w,
        height: 24.h,
        colorFilter: ColorFilter.mode(KudoColors.black, BlendMode.srcIn),
      ).inkWell(onTap: _showReportDialog),
    ].toRow().paddingHorizontal(16.w).paddingVertical(12.h);
  }

  /// 构建聊天区域
  Widget _buildChatArea() {
    final messages = KiteTeamController.globalInstance.currentTeamMessagesState
        .reactiveValue(context);

    return Container(
      decoration: BoxDecoration(
        color: KudoColors.chatBackground,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(24.r),
          topRight: Radius.circular(24.r),
        ),
      ),
      child:
          messages.isEmpty ? _buildEmptyChat() : _buildMessagesList(messages),
    ).expanded();
  }

  /// 构建空聊天状态
  Widget _buildEmptyChat() {
    return [
      Icon(
        Icons.chat_bubble_outline,
      ).iconSize(64.sp).iconColor(KudoColors.black.withValues(alpha: 0.6)),
      SizedBox(height: 16.h),
      Text('Start the conversation!')
          .fontSize(16.sp)
          .textColor(KudoColors.black.withValues(alpha: 0.8))
          .fontFamily(GoogleFonts.lato().fontFamily),
    ].toColumn(mainAxisAlignment: MainAxisAlignment.center).center();
  }

  /// 构建消息列表
  Widget _buildMessagesList(List<KiteTeamChatEntity> messages) {
    return Padding(
      padding: EdgeInsets.all(16.w),
      child: ListView.builder(
        controller: _scrollController,
        itemCount: messages.length,
        itemBuilder: (context, index) {
          return _buildMessageItem(messages[index]);
        },
      ),
    );
  }

  /// 构建单个消息项
  Widget _buildMessageItem(KiteTeamChatEntity message) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    final isMyMessage =
        currentUser?.uniqueIdentifier == message.senderPersonaId;
    final sender = PersonaSessionController.quickGetUserById(
      message.senderPersonaId,
    );

    return [
      // 左侧头像（他人消息）
      if (!isMyMessage) ...[
        ImageResourceHelper.buildCircularAvatar(
          imagePath: sender?.avatarResourceUrl ?? '',
          radius: 20.r,
        ),
        SizedBox(width: 8.w),
      ],

      // 消息气泡区域
      [
            // 发送者名称（他人消息）
            if (!isMyMessage)
              Text(sender?.displayAlias ?? 'Unknown')
                  .fontSize(12.sp)
                  .textColor(KudoColors.black.withValues(alpha: 0.8))
                  .fontFamily(GoogleFonts.lato().fontFamily)
                  .paddingBottom(4.h),

            // 消息气泡
            Container(
              decoration: BoxDecoration(
                color: isMyMessage ? KudoColors.yellow : KudoColors.green,
                borderRadius: BorderRadius.only(
                  topLeft:
                      isMyMessage
                          ? Radius.circular(24.r)
                          : Radius.circular(10.r),
                  topRight:
                      isMyMessage
                          ? Radius.circular(10.r)
                          : Radius.circular(24.r),
                  bottomLeft: Radius.circular(24.r),
                  bottomRight: Radius.circular(24.r),
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black,
                    offset: Offset(0, 4),
                    blurRadius: 0,
                  ),
                ],
              ),
              child: Text(message.messageContent)
                  .fontSize(14.sp)
                  .textColor(KudoColors.black)
                  .fontFamily(GoogleFonts.lato().fontFamily)
                  .paddingHorizontal(16.w)
                  .paddingVertical(12.h),
            ),
          ]
          .toColumn(
            crossAxisAlignment:
                isMyMessage ? CrossAxisAlignment.end : CrossAxisAlignment.start,
          )
          .expanded(),

      // 右侧头像（我的消息）
      if (isMyMessage) ...[
        SizedBox(width: 8.w),
        ImageResourceHelper.buildCircularAvatar(
          imagePath: currentUser?.avatarResourceUrl ?? '',
          radius: 20.r,
        ),
      ],
    ].toRow(crossAxisAlignment: CrossAxisAlignment.start).paddingBottom(16.h);
  }

  /// 构建消息输入区域
  Widget _buildMessageInput() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.transparent,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(24.r),
          topRight: Radius.circular(24.r),
        ),
      ),
      child: Container(
        height: 50.h,
        margin: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: KudoColors.yellow,
          borderRadius: BorderRadius.circular(25.r),
          boxShadow: [
            BoxShadow(color: Colors.black, offset: Offset(0, 4), blurRadius: 0),
          ],
        ),
        child: Row(
          children: [
            // 输入框
            Expanded(
              child: TextField(
                controller: _messageController,
                decoration: InputDecoration(
                  hintText: 'Start Telling Your Story',
                  hintStyle: TextStyle(
                    fontSize: 14.sp,
                    color: KudoColors.black.withValues(alpha: 0.5),
                    fontFamily: GoogleFonts.lato().fontFamily,
                  ),
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(horizontal: 16.w),
                ),
                style: TextStyle(
                  fontSize: 14.sp,
                  color: KudoColors.black,
                  fontFamily: GoogleFonts.lato().fontFamily,
                ),
                maxLines: 1,
                textInputAction: TextInputAction.send,
                onSubmitted: (_) => _sendMessage(),
              ),
            ),

            // 发送按钮
            Container(
              width: 36.w,
              height: 36.h,
              margin: EdgeInsets.only(right: 7.w),
              decoration: BoxDecoration(
                color: KudoColors.black,
                shape: BoxShape.circle,
              ),
              child:
                  SvgPicture.asset(
                    'assets/svg/send.svg',
                    width: 18.w,
                    height: 18.h,
                    colorFilter: ColorFilter.mode(
                      KudoColors.yellow,
                      BlendMode.srcIn,
                    ),
                  ).center(),
            ).inkWell(onTap: _sendMessage),
          ],
        ),
      ),
    );
  }

  /// 发送消息
  void _sendMessage() {
    final messageText = _messageController.text.trim();
    if (messageText.isEmpty) return;

    final success = KiteTeamController.globalInstance.sendTeamChatMessage(
      widget.teamData.uniqueIdentifier,
      messageText,
    );

    if (success) {
      _messageController.clear();
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _scrollToBottom();
      });
    }
  }

  void _showReportDialog() {
    ReportDialog.show(
      context: context,
      title: 'Report Team Chat',
      onReport: (reportType) {
        _handleReportSubmitted();
      },
    );
  }

  void _handleReportSubmitted() {
    KudoToast.showSuccessToast(context, 'Report submitted successfully');

    KiteTeamController.globalInstance.clearTeamMessages(
      widget.teamData.uniqueIdentifier,
    );

    GoRouter.of(context).pop();
  }
}
